package com.module.overview.ui.cardHistoryDetails.provider

import android.graphics.Typeface
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.widget.LinearLayoutCompat
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.home.ScoringFactorsModel
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.data.repository.HomeApi
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.data.CommonBean
import com.common.base.utils.AppUtils
import com.common.base.utils.JsonUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getColor
import com.common.base.utils.ViewUtils.getString
import com.module.ble.data.bean.CusChartData
import com.module.ble.repo.HeartRateRepo
import com.module.ble.repo.SleepInfoRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.groupSleepDataByQualityAndTime
import com.module.ble.widget.SleepOptimalRangeProgressBar
import com.module.overview.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import rxhttp.toFlow
import rxhttp.wrapper.param.RxHttp
import kotlin.math.absoluteValue

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/08/12
 *
 * 描述：睡眠总结卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvSleepSummaryCardProvider(time:Long,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SLEEP_SUMMARY_PERIOD,
    override val layoutId: Int = R.layout.overview_sleep_summary_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time
    private val curTimePair = TimeUtils.getTimeRangeForSleep(curTime)

    var theDaySleepDuration = -1L//睡眠总时长，单位：分钟
    var theDayStayBedDuration = -1L//卧床总时长，单位：分钟

    var sevenDaySleepTotalDuration = -1L // 7天睡眠总时长（眼动+浅睡+深睡（不含卧床时间、清醒时间、小睡））
    var sevenDayStayBedTotalDuration = -1L // 7天卧床时长（眼动+浅睡+深睡+卧床时间+清醒时间；（不含小睡））

    // 近7天（有数据的天数）平均睡眠总时长（分钟）
    var averageSevenDaysTotalMinutes = -1L
    // 近7天（有数据的天数）平均卧床时长（分钟）
    var averageStayBedTotalDuration = -1L

    var theDaySleepEfficiency = -1//睡眠效率
    var sevenDayAverageSleepEfficiency = -1//睡眠效率

    var theDayAverageHr = -1//当天平均心率
    var sevenDayAverageHr = -1//7天平均心率

    var theDayTotalSleepScore = -1//当天睡眠总分
    var sevenDayTotalSleepScore = -1//7天平均睡眠总分

    private var requestJob: Job? = null
    var scope = CoroutineScope(Dispatchers.IO)

    private var llStayDurationCk: TextView? = null
    private var llSleepEfficiencyCk : TextView? = null
    private var llSleepHrCk : TextView? = null
    private var llSleepTotalScoreCk : TextView? = null
    private var tvSummary: TextView? = null

//    private var tvStayDurationHint : TextView? = null
//    private var tvSleepEfficiencyHint : TextView? = null
//    private var tvSleepHrHint : TextView? = null
//    private var tvSleepTotalScoreHint : TextView? = null

//    private var tvStayDuration : TextView? = null
//    private var tvSleepEfficiency : TextView? = null
//    private var tvSleepHr : TextView? = null
//    private var tvSleepTotalScore : TextView? = null


    private var sbrLastNight: ProgressBar? = null
    private var sbrLastWeek: ProgressBar? = null
    private var tvLastNight : TextView? = null
    private var tvLastWeekHint : TextView? = null
    private var tvLast : TextView? = null
    private var tvLastWeek : TextView? = null


    private val commonRailUnit = getString(R.string.common_rail_unit)

    private val summaryPdSleepHint = "${getString(R.string.overview_sleep_summary_pd_hint)}${getString(R.string.common_sleep_hint)}${getString(R.string.overview_sleep_summary_pd_hint2)}"

    init {
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {

        setAllDefSelect()

        tvLastNight?.text = TimeUtils.getMonthDay(curTime)

        val timeRanges = mutableListOf<Pair<Long, Long>>()
        for (day in 1..7) {// 获取前7天的时间范围（含今天）
            val timeRange = TimeUtils.getTimeRangeForSleep(curTime, day)
            timeRanges.add(timeRange)
        }
        tvLastWeekHint?.text = "${TimeUtils.getMonthDay(timeRanges[0].second)}-${TimeUtils.getMonthDay(timeRanges[6].second)}"

        getNightSleepData()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvSummary = viewHolder.getView(R.id.tvSummary)

        llStayDurationCk = viewHolder.getView(R.id.llStayDurationCk)
        llSleepEfficiencyCk = viewHolder.getView(R.id.llSleepEfficiencyCk)
        llSleepHrCk = viewHolder.getView(R.id.llSleepHrCk)
        llSleepTotalScoreCk = viewHolder.getView(R.id.llSleepTotalScoreCk)

        sbrLastNight = viewHolder.getView(R.id.sbrLastNight)
        sbrLastWeek = viewHolder.getView(R.id.sbrLastWeek)
        tvLastNight = viewHolder.getView(R.id.tvLastNight)
        tvLastWeekHint = viewHolder.getView(R.id.tvLastWeekHint)
        tvLast = viewHolder.getView(R.id.tvLast)
        tvLastWeek = viewHolder.getView(R.id.tvLastWeek)

//        tvStayDurationHint = viewHolder.getView(R.id.tvStayDurationHint)
//        tvSleepEfficiencyHint = viewHolder.getView(R.id.tvSleepEfficiencyHint)
//        tvSleepHrHint = viewHolder.getView(R.id.tvSleepHrHint)
//        tvSleepTotalScoreHint = viewHolder.getView(R.id.tvSleepTotalScoreHint)
//        tvStayDuration = viewHolder.getView(R.id.tvStayDuration)
//        tvSleepEfficiency = viewHolder.getView(R.id.tvSleepEfficiency)
//        tvSleepHr = viewHolder.getView(R.id.tvSleepHr)
//        tvSleepTotalScore = viewHolder.getView(R.id.tvSleepTotalScore)

        llStayDurationCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()
                    tvLast?.text = commonRailUnit
                    tvLastWeek?.text = commonRailUnit
                    setStayDurationCkData(true)
                }
            }
        }

        llSleepEfficiencyCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()
                    tvLast?.text = commonRailUnit
                    tvLastWeek?.text = commonRailUnit
                    setSleepEfficiencyCkData(true)
                }
            }
        }

        llSleepHrCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()
                    tvLast?.text = commonRailUnit
                    tvLastWeek?.text = commonRailUnit
                    setSleepHrCkData(true)
                }
            }
        }

        llSleepTotalScoreCk?.let { viewIt ->
            viewIt.setOnClickListener {
                viewIt.isSelected.yes {
                    setAllPillarNotSelect()
                }.otherwise {
                    setAllPillarNotSelect()

                    tvLast?.text = commonRailUnit
                    tvLastWeek?.text = commonRailUnit

                    setSleepTotalScoreCkData(true)
                }
            }
        }

        setAllPillarNotSelect()

        super.onViewHolderCreated(viewHolder, viewType)
    }

    private fun setAllDefSelect(){
        llStayDurationCk?.let { viewIt ->
            SpanUtils.create()
                .addForeColorSection(
                    "${getString(R.string.overview_stay_duration_hint)}\n",
                    getColor(R.color.c_7f7f7f)
                )
                .addForeColorSection(
                    commonRailUnit,
                    getColor(R.color.text_content)
                )
                .setAbsSize(commonRailUnit, 16)
                .showIn(viewIt)
        }
        llSleepEfficiencyCk?.let { viewIt ->
            SpanUtils.create()
                .addForeColorSection(
                    "${getString(R.string.overview_sleep_efficiency_hint)}\n",
                    getColor(R.color.c_7f7f7f)
                )
                .addForeColorSection(
                    commonRailUnit,
                    getColor(R.color.text_content)
                )
                .setAbsSize(commonRailUnit, 16)
                .showIn(viewIt)
        }
        llSleepHrCk?.let { viewIt ->
            SpanUtils.create()
                .addForeColorSection(
                    "${getString(R.string.overview_sleep_hr_hint)}\n",
                    getColor(R.color.c_7f7f7f)
                )
                .addForeColorSection(
                    commonRailUnit,
                    getColor(R.color.text_content)
                )
                .setAbsSize(commonRailUnit, 16)
                .addSection("${getString(R.string.common_times_per_minute_splice)}")
                .showIn(viewIt)
        }
        llSleepTotalScoreCk?.let { viewIt ->
            SpanUtils.create()
                .addForeColorSection(
                    "${getString(R.string.overview_total_sleep_score_hint)}\n",
                    getColor(R.color.c_7f7f7f)
                )
                .addForeColorSection(
                    commonRailUnit,
                    getColor(R.color.text_content)
                )
                .setAbsSize(commonRailUnit, 16)
                .addSection("${getString(R.string.common_score_hint)}")
                .showIn(viewIt)
        }
        llStayDurationCk?.isSelected = false
        llSleepEfficiencyCk?.isSelected = false
        llSleepHrCk?.isSelected = false
        llSleepTotalScoreCk?.isSelected = false
    }

    private fun setAllPillarNotSelect(){

        llStayDurationCk?.isSelected = false
        llSleepEfficiencyCk?.isSelected = false
        llSleepHrCk?.isSelected = false
        llSleepTotalScoreCk?.isSelected = false

        setStayDurationCkData()
        setSleepEfficiencyCkData()
        setSleepHrCkData()
        setSleepTotalScoreCkData()


        (theDaySleepDuration >=0).yes {
            tvLast?.text = TimeUtils.formatTime((theDaySleepDuration*60000), showHour = true, showMin = true)
        }
        (averageSevenDaysTotalMinutes >=0).yes {
            tvLastWeek?.text = TimeUtils.formatTime((averageSevenDaysTotalMinutes*60000), showHour = true, showMin = true)
        }

        (theDaySleepDuration>0 && averageSevenDaysTotalMinutes>0).yes {
            val mDenominator = if(theDaySleepDuration > averageSevenDaysTotalMinutes) theDaySleepDuration.toString() else averageSevenDaysTotalMinutes.toString()
            sbrLastNight?.progress =  ((MathUtil.div(theDaySleepDuration.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
            sbrLastWeek?.progress = ((MathUtil.div(averageSevenDaysTotalMinutes.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
        }

        changeTvSummaryUi()
    }

    fun changeTvSummaryUi(){
        val diff = theDaySleepDuration - averageSevenDaysTotalMinutes
        when {
            diff > 0L -> {//大于
                tvSummary?.let { viewIt ->
                    SpanUtils.create()
                        .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                        .addForeColorSection(
                            "${getString(R.string.overview_sleep_duration_hint)}",
                            getColor(R.color.c_9966ff)
                        )
                        .addSection(getString(R.string.overview_sleep_summary_pd_increase_hint))
                        .addSection(TimeUtils.formatTime((diff.absoluteValue *60000), showHour = true, showMin = true))
                        .showIn(viewIt)
                }
            }
            diff == 0L-> {//等于
                tvSummary?.text = summaryPdSleepHint
            }
            else -> {//小于
                tvSummary?.let { viewIt ->
                    SpanUtils.create()
                        .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                        .addForeColorSection(
                            "${getString(R.string.overview_sleep_duration_hint)}",
                            getColor(R.color.c_9966ff)
                        )
                        .addSection(getString(R.string.overview_sleep_summary_pd_reduce_hint))
                        .addSection(TimeUtils.formatTime((diff.absoluteValue *60000), showHour = true, showMin = true))
                        .showIn(viewIt)
                }
            }
        }
    }

    fun setStayDurationCkData(isSelect: Boolean =false){
        val tvLastStr = if(theDaySleepEfficiency >=0) (TimeUtils.formatTime((theDayStayBedDuration*60000), showHour = true, showMin = true)?:commonRailUnit) else commonRailUnit
        val tvLastSList = TimeUtils.formatTimeToList(theDayStayBedDuration*60000)
        llStayDurationCk?.let { viewIt ->
            SpanUtils.create()
                .addForeColorSection(
                    "${getString(R.string.overview_stay_duration_hint)}\n",
                   if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.c_7f7f7f)
                )
                .addForeColorSection(
                    tvLastSList[1].toString(),
                    if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.text_content)
                )
                .setAbsSize(tvLastSList[1].toString(), 16)
                .setStyle(tvLastSList[1].toString(), Typeface.BOLD)
                .addForeColorSection(
                    AppUtils.getString(R.string.common_hours_hint),
                    if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.text_content)
                )
                .addForeColorSection(
                    tvLastSList[2].toString(),
                    if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.text_content)
                )
                .setAbsSize(tvLastSList[2].toString(), 16)
                .setStyle(tvLastSList[2].toString(), Typeface.BOLD)
                .addForeColorSection(
                    AppUtils.getString(R.string.common_score_hint),
                    if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.text_content)
                )
                .showIn(viewIt)
        }

        isSelect.yes {

            (theDayStayBedDuration >=0).yes {
                tvLast?.text = tvLastStr
            }
            (averageStayBedTotalDuration >=0).yes {
                tvLastWeek?.text = TimeUtils.formatTime((averageStayBedTotalDuration*60000), showHour = true, showMin = true)
            }
            (theDayStayBedDuration>0 || averageStayBedTotalDuration>0).yes {
                val mDenominator = if(theDayStayBedDuration > averageStayBedTotalDuration) theDayStayBedDuration.toString() else averageStayBedTotalDuration.toString()
                sbrLastNight?.progress =  ((MathUtil.div(theDayStayBedDuration.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
                sbrLastWeek?.progress = ((MathUtil.div(averageStayBedTotalDuration.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
            }.otherwise {
                sbrLastNight?.progress =  0
                sbrLastWeek?.progress = 0
            }


            val diff = theDayStayBedDuration - averageStayBedTotalDuration
            when {
                diff > 0L -> {//大于
                    tvSummary?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_stay_duration_hint)}",
                                getColor(R.color.c_9966ff)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_increase_hint))
                            .addSection(TimeUtils.formatTime((diff.absoluteValue *60000), showHour = true, showMin = true))
                            .showIn(viewIt)
                    }
                }
                diff == 0L-> {//等于
                    tvSummary?.text = "${getString(R.string.overview_sleep_summary_pd_hint)}${getString(R.string.overview_stay_duration_hint)}${getString(R.string.overview_sleep_summary_pd_hint2)}"
                }
                else -> {//小于
                    tvSummary?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_stay_duration_hint)}",
                                getColor(R.color.c_9966ff)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_reduce_hint))
                            .addSection(TimeUtils.formatTime((diff.absoluteValue *60000), showHour = true, showMin = true))
                            .showIn(viewIt)
                    }
                }
            }
        }

        llStayDurationCk?.isSelected = isSelect
    }

    fun setSleepEfficiencyCkData(isSelect: Boolean =false){
        val tvLastStr = if(theDaySleepEfficiency >=0) theDaySleepEfficiency.toString() else commonRailUnit

        llSleepEfficiencyCk?.let { viewIt ->
            SpanUtils.create()
                .addForeColorSection(
                    "${getString(R.string.overview_sleep_efficiency_hint)}\n",
                    if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.c_7f7f7f)
                )
                .addForeColorSection(
                    tvLastStr,
                    if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.text_content)
                )
                .setAbsSize(tvLastStr, 16)
                .setStyle(tvLastStr, Typeface.BOLD)
                .addForeColorSection("${getString(R.string.common_bfb_unit)}",if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.text_content))
                .showIn(viewIt)
        }

        isSelect.yes {
            (theDaySleepEfficiency >=0).yes {
                tvLast?.text = "$tvLastStr${getString(R.string.common_bfb_unit)}"
            }
            (sevenDayAverageSleepEfficiency >=0).yes {
                tvLastWeek?.text = "$sevenDayAverageSleepEfficiency${getString(R.string.common_bfb_unit)}"
            }

            (theDaySleepEfficiency>0 || sevenDayAverageSleepEfficiency>0).yes {
                val mDenominator = if(theDaySleepEfficiency > sevenDayAverageSleepEfficiency) theDaySleepEfficiency.toString() else sevenDayAverageSleepEfficiency.toString()
                sbrLastNight?.progress =  ((MathUtil.div(theDaySleepEfficiency.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
                sbrLastWeek?.progress = ((MathUtil.div(sevenDayAverageSleepEfficiency.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
            }.otherwise {
                sbrLastNight?.progress =  0
                sbrLastWeek?.progress = 0
            }

            val diff = theDaySleepEfficiency - sevenDayAverageSleepEfficiency
            when {
                diff > 0 -> {//大于
                    tvSummary?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_sleep_efficiency_hint)}",
                                getColor(R.color.c_9966ff)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_increase_hint))
                            .addSection(diff.absoluteValue.toString())
                            .addSection("${getString(R.string.common_bfb_unit)}")
                            .showIn(viewIt)
                    }
                }
                diff == 0-> {//等于
                    tvSummary?.text = "${getString(R.string.overview_sleep_summary_pd_hint)}${getString(R.string.overview_sleep_efficiency_hint)}${getString(R.string.overview_sleep_summary_pd_hint2)}"
                }
                else -> {//小于
                    tvSummary?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_sleep_efficiency_hint)}",
                                getColor(R.color.c_9966ff)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_reduce_hint))
                            .addSection(diff.absoluteValue.toString())
                            .addSection("${getString(R.string.common_bfb_unit)}")
                            .showIn(viewIt)
                    }
                }
            }
        }
        llSleepEfficiencyCk?.isSelected = isSelect
    }

    fun setSleepHrCkData( isSelect: Boolean =false){
        val tvLastStr = if(theDayAverageHr >=0) theDayAverageHr.toString() else commonRailUnit
        llSleepHrCk?.let { viewIt ->
            SpanUtils.create()
                .addForeColorSection(
                    "${getString(R.string.overview_sleep_hr_hint)}\n",
                    if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.c_7f7f7f)
                )
                .addForeColorSection(
                    tvLastStr,
                    if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.text_content)
                )
                .setAbsSize(tvLastStr, 16)
                .setStyle(tvLastStr, Typeface.BOLD)
                .addForeColorSection("${getString(R.string.common_times_per_minute_splice)}",if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.text_content))
                .showIn(viewIt)
        }

        isSelect.yes {
            (theDayAverageHr >=0).yes {
                tvLast?.text =  "$tvLastStr${getString(R.string.common_times_per_minute_splice)}"
            }
            (sevenDayAverageHr >=0).yes {
                tvLastWeek?.text = "$sevenDayAverageHr${getString(R.string.common_times_per_minute_splice)}"
            }

            (theDayAverageHr>0 || sevenDayAverageHr>0).yes {
                val mDenominator = if(theDayAverageHr > sevenDayAverageHr) theDayAverageHr.toString() else sevenDayAverageHr.toString()
                sbrLastNight?.progress =  ((MathUtil.div(theDayAverageHr.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
                sbrLastWeek?.progress = ((MathUtil.div(sevenDayAverageHr.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
            }.otherwise {
                sbrLastNight?.progress =  0
                sbrLastWeek?.progress = 0
            }


            val diff = theDayAverageHr - sevenDayAverageHr
            when {
                diff > 0 -> {//大于
                    tvSummary?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_sleep_hr_hint)}",
                                getColor(R.color.c_9966ff)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_increase_hint))
                            .addSection(diff.absoluteValue.toString())
                            .addSection("${getString(R.string.common_times_per_minute_splice)}")
                            .showIn(viewIt)
                    }
                }
                diff == 0-> {//等于
                    tvSummary?.text = "${getString(R.string.overview_sleep_summary_pd_hint)}${getString(R.string.overview_sleep_hr_hint)}${getString(R.string.overview_sleep_summary_pd_hint2)}"
                }
                else -> {//小于
                    tvSummary?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_sleep_hr_hint)}",
                                getColor(R.color.c_9966ff)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_reduce_hint))
                            .addSection(diff.absoluteValue.toString())
                            .addSection("${getString(R.string.common_times_per_minute_splice)}")
                            .showIn(viewIt)
                    }
                }
            }
        }
        llSleepHrCk?.isSelected = isSelect
    }

    fun setSleepTotalScoreCkData(isSelect: Boolean =false){

        val tvLastStr = if(theDayTotalSleepScore >=0) theDayTotalSleepScore.toString() else commonRailUnit

        llSleepTotalScoreCk?.let { viewIt ->
            SpanUtils.create()
                .addForeColorSection(
                    "${getString(R.string.overview_total_sleep_score_hint)}\n",
                    if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.c_7f7f7f)
                )
                .addForeColorSection(
                    tvLastStr,
                    if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.text_content)
                )
                .setAbsSize(tvLastStr, 16)
                .addForeColorSection("${getString(R.string.common_score_hint)}",if (isSelect) getColor(R.color.c_9966ff) else getColor(R.color.text_content))
                .showIn(viewIt)
        }

        isSelect.yes {
            (theDayTotalSleepScore >=0).yes {
                tvLast?.text = "$tvLastStr${getString(R.string.common_score_hint)}"
            }
            (sevenDayTotalSleepScore >=0).yes {
                tvLastWeek?.text = "$sevenDayTotalSleepScore${getString(R.string.common_score_hint)}"
            }

            (theDayTotalSleepScore>0 || sevenDayTotalSleepScore>0).yes {
                val mDenominator = if(theDayTotalSleepScore > sevenDayTotalSleepScore) theDayTotalSleepScore.toString() else sevenDayTotalSleepScore.toString()
                sbrLastNight?.progress =  ((MathUtil.div(theDayTotalSleepScore.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
                sbrLastWeek?.progress = ((MathUtil.div(sevenDayTotalSleepScore.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
            }.otherwise {
                sbrLastNight?.progress =  0
                sbrLastWeek?.progress = 0
            }


            val diff = theDayTotalSleepScore - sevenDayTotalSleepScore
            when {
                diff > 0 -> {//大于
                    tvSummary?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_total_sleep_score_hint)}",
                                getColor(R.color.c_9966ff)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_increase_hint))
                            .addSection(diff.absoluteValue.toString())
                            .addSection("${getString(R.string.common_score_hint)}")
                            .showIn(viewIt)
                    }
                }
                diff == 0-> {//等于
                    tvSummary?.text = "${getString(R.string.overview_sleep_summary_pd_hint)}${getString(R.string.overview_total_sleep_score_hint)}${getString(R.string.overview_sleep_summary_pd_hint2)}"
                }
                else -> {//小于
                    tvSummary?.let { viewIt ->
                        SpanUtils.create()
                            .addSection(getString(R.string.overview_sleep_summary_pd_hint3))
                            .addForeColorSection(
                                "${getString(R.string.overview_total_sleep_score_hint)}",
                                getColor(R.color.c_9966ff)
                            )
                            .addSection(getString(R.string.overview_sleep_summary_pd_reduce_hint))
                            .addSection(diff.absoluteValue.toString())
                            .addSection("${getString(R.string.common_score_hint)}")
                            .showIn(viewIt)
                    }
                }
            }
        }
        llSleepTotalScoreCk?.isSelected = isSelect
    }

    /**
     * 获取昨晚睡眠数据
     */
    private fun getNightSleepData(){
        if (curTime <=0 ) return
        doOnIOThread {
            SleepInfoRepo.instance.findByTimeRangeByNight(curTimePair.first, curTimePair.second)?.let {listIt->
                listIt.sortedBy { it.createdTime }//按时间排序（升序）
//                LogUtils.d("OvSleepPeriodCardProvider", "YQ: allSleepData ${JsonUtils.toJson(listIt)}")
                val sleepData: MutableList<CusChartData>
                if (listIt.isNotEmpty()) {
                    theDaySleepDuration = 0
                    theDayStayBedDuration = 0
                    sleepData = groupSleepDataByQualityAndTime(listIt) as MutableList<CusChartData>
                    sleepData.forEach {sleepDataIt->
                        theDaySleepDuration += if (sleepDataIt.status==1||sleepDataIt.status==2||sleepDataIt.status==3) sleepDataIt.timeLong else 0
                        theDayStayBedDuration += sleepDataIt.timeLong
                    }

                    theDaySleepEfficiency = ((MathUtil.div(theDaySleepDuration.toString(),theDayStayBedDuration.toString(),false)?:"0").toFloat() * 100).toInt()

                    doOnUiThread {
                        tvLast?.text = TimeUtils.formatTime((theDaySleepDuration*60000), showHour = true, showMin = true)

                        setStayDurationCkData()
                        setSleepEfficiencyCkData()
                    }

                    getSevenNightSleepData()
                    getSleepTheDayHr()
                }
            }
        }
    }

    /**
     * 获取近7天睡眠数据
     */
    private fun getSevenNightSleepData(){
        if (curTime <=0 ) return
        doOnIOThread {
            val timeRanges = mutableListOf<Pair<Long, Long>>()
            for (day in 1..7) {// 获取前7天的时间范围（含今天）
                val timeRange = TimeUtils.getTimeRangeForSleep(curTime, day)
                timeRanges.add(timeRange)
            }
            SleepInfoRepo.instance.findByMultiTimeRangesNight(timeRanges)?.let {listIt->

                listIt.sortedBy { it.createdTime }//按时间排序（升序）

                val ranges = timeRanges.toList()
                val perDayData = ranges.map { (start, end) ->
                    listIt
                        .filter { it.createdTime in start until end }
                        .sortedBy { it.createdTime }
                }

                // 生成带“日期标签”的配对列表（label 使用每日起点日期）
                val perDayPairs = ranges.mapIndexed { index, (start, _) ->
                    TimeUtils.getYearMonthDay(start) to perDayData[index]
                }

//                val perDayPairsStr = JsonUtils.toJson(perDayPairs)
                // 在获得 perDayPairs 后过滤掉 second 为空集合的项
                val perDayPairsNonEmpty = perDayPairs.filter { it.second.isNotEmpty() }
//                val perDayPairsNonEmptyStr = JsonUtils.toJson(perDayPairsNonEmpty)

                // 遍历每天，计算每天的五个时长，并累计 theDayTotalDuration
                var dayCountWithData = 0

                sevenDayStayBedTotalDuration = 0
                sevenDaySleepTotalDuration = 0

                perDayPairsNonEmpty.forEach { perDayPairsIt ->
                    val dayList = perDayPairsIt.second
                    if (dayList.isEmpty()) return@forEach

                    val sleepData = groupSleepDataByQualityAndTime(dayList)

                    var theDayTotalDuration = 0L // 当天睡眠总时长（分钟）

                    sleepData.forEach { sleepDataIt ->
                        // 只累计睡眠阶段（1:REM 2:浅睡 3:深睡）到总时长
                        if (sleepDataIt.status == 1 || sleepDataIt.status == 2 || sleepDataIt.status == 3) {
                            theDayTotalDuration += sleepDataIt.timeLong
                        }

                        sevenDayStayBedTotalDuration += sleepDataIt.timeLong
                    }

                    // 累计每天的睡眠总时长，用于之后求平均
                    sevenDaySleepTotalDuration += theDayTotalDuration
                    dayCountWithData += 1

                    // 如需调试每天的统计，可在此打印/记录 perDayPairsIt.first(日期) 和上述五个时长
                    // Log.d("SleepSummary", "${perDayPairsIt.first}: total=$theDayTotalDuration, awake=$theDayAwakeDuration, light=$theDayLightDuration, rem=$theDayRemDuration, deep=$theDayDeepDuration")
                }

                // 近7天（有数据的天数）平均睡眠总时长（分钟）
                averageSevenDaysTotalMinutes = sevenDaySleepTotalDuration / dayCountWithData

                // 近7天（有数据的天数）平均卧床时长（分钟）
                averageStayBedTotalDuration = sevenDayStayBedTotalDuration / dayCountWithData

                sevenDayAverageSleepEfficiency = ((MathUtil.div(averageSevenDaysTotalMinutes.toString(),averageStayBedTotalDuration.toString(),false)?:"0").toFloat() * 100).toInt()

                // 可选：更新 UI，显示“近7天平均睡眠时长”
                doOnUiThread {
                    tvLastWeek?.text = TimeUtils.formatTime((averageSevenDaysTotalMinutes*60000), showHour = true, showMin = true)

                    (theDaySleepDuration>0 && averageSevenDaysTotalMinutes>0).yes {
                        val mDenominator = if(theDaySleepDuration > averageSevenDaysTotalMinutes) theDaySleepDuration.toString() else averageSevenDaysTotalMinutes.toString()
                        sbrLastNight?.progress =  ((MathUtil.div(theDaySleepDuration.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
                        sbrLastWeek?.progress = ((MathUtil.div(averageSevenDaysTotalMinutes.toString(),mDenominator,false)?:"0").toFloat() * 100).toInt()
                    }

                    changeTvSummaryUi()
                }
            }
        }
    }

    /**
     * 获取当天心率
     */
    private fun getSleepTheDayHr(){
        if (curTime <=0 ) return

        //睡眠心率
        HeartRateRepo.instance.findByTimeRange(curTimePair.first, curTimePair.second)?.let { listIt->
            if (listIt.isNullOrEmpty()) return

//            val listItStr = JsonUtils.toJson(listIt)

            theDayAverageHr = if (listIt.isNotEmpty()) {//当日平均
                listIt.map { it.heartRate }.average().toInt()
            } else {
                -1
            }

            doOnUiThread {
                setSleepHrCkData()
            }

            getSevenNightsDayHr()
        }
    }


    /**
     * 获取近7天睡眠心率数据并构建时间段数组
     */
    private fun getSevenNightsDayHr(){
        if (curTime <=0 ) return
        doOnIOThread {
            val timeRanges = mutableListOf<Pair<Long, Long>>()
            for (day in 1..7) {// 获取前7天的时间范围（含今天）
                val timeRange = TimeUtils.getTimeRangeForSleep(curTime, day)
                timeRanges.add(timeRange)
            }

            // 使用构建的timeRanges查询多时间段数据
            HeartRateRepo.instance.findByMultiTimeRanges(timeRanges)?.let { hrOriginalListIt->
//                val hrOriginalListItStr = JsonUtils.toJson(hrOriginalListIt)
                sevenDayAverageHr = if (hrOriginalListIt.isNotEmpty()) {//7日平均
                    hrOriginalListIt.map { it.heartRate }.average().toInt()
                } else {
                    -1
                }
            }
        }
    }



    // 手动取消请求
    fun cancelRequest() {
        requestJob?.cancel()
        requestJob = null
    }

    private fun getSleepScoringFactors() {
        // 取消之前的请求
        requestJob?.cancel()

        requestJob = scope.launch {
            RxHttp.postJson(HomeApi.GET_SIGNS_SCORING_FACTORS)
                .add("date", TimeUtils.getYearMonthDay(curTime))
                .toFlow<CommonBean<ScoringFactorsModel>>()
                .catch { e ->
                    // 处理异常
                }.collect { responseIt->
                    responseIt.isSuccess().yes {
                        responseIt.Data?.let { dataIt->
                            doOnUiThread {
                            }
                        }
                    }
                }
        }
    }
}